<template>
  <div class="header">
    <div class="header-left">节目名称</div>
    <div class="header-center">
      <ComponentList />
    </div>
    <div class="header-right">
      <el-button size="mini" type="primary" @click="save">保存</el-button>
      <el-button size="mini" type="primary" @click="preview">预览</el-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import eventBus from '@/utils/eventBus'
import ComponentList from '@/components/ComponentList'
import { forEach } from 'lodash' // 左侧列表组件

export default {
  name: 'HeaderTool',
  components: {
    ComponentList,
  },
  data() {
    return {
      isShowPreview: false,
      isShowAceEditor: false,
      timer: null,
      isScreenshot: false,
      scale: 100,
      switchValue: false,
      isShowDialog: false,
      jsonData: '',
      isExport: false,
    }
  },
  computed: {
    ...mapState(['componentData', 'canvasStyleData', 'areaData', 'curComponent', 'curComponentIndex', 'isDarkMode']),
  },
  created() {
    eventBus.$on('preview', this.preview)
  },
  methods: {
    preview() {
      this.$alert('预览需要保存当前数据', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          // 增加保存接口调用 成功回调跳转预览页面

          // 传入id到预览页面，预览页面通过接口请求   注意：预览需要将当前页面保存
          window.open(`/#/preview?id=${1}`)
        },
      })
    },
    save() {
      const changePageData = this.changeAllComponentData(JSON.parse(JSON.stringify(this.canvasStyleData)))

      localStorage.setItem('DEMO_TEXT_PAGE_DATA', JSON.stringify(this.canvasStyleData))
      // 每个页面数据及区域数据
      console.log(changePageData)
      this.$message.success('保存成功')
    },
    // 将数据的缩放改为100%比例
    changeAllComponentData(canvasStyleData) {
      forEach(canvasStyleData, (item) => {
        const currentScale = item.scale / 100 // 转换为小数形式
        forEach(item.componentData, (child) => {
          if (child.width) {
            child.width = Math.round(child.width / currentScale)
          }
          if (child.height) {
            child.height = Math.round(child.height / currentScale)
          }
          // 如果有其他需要调整的属性，如 left, top 等，可以类似地处理
          if (child.left) {
            child.left = Math.round(child.left / currentScale)
          }
          if (child.top) {
            child.top = Math.round(child.top / currentScale)
          }
        })
        item.scale = 100
      })
      return canvasStyleData
    },
  },
}
</script>

<style lang="scss" scoped>
.header {
  padding: 5px 10px;
  white-space: nowrap;
  overflow-x: auto;
  background: var(--main-bg-color);
  border-color: var(--ace-bg-color);
  border-bottom: 1px solid var(--border-color);
  display: flex;
  &-left,
  &-right {
    width: 200px;
  }
  &-center {
    flex: 1 1 auto;
  }
  &-right {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  &-left {
    line-height: 40px;
  }
}
</style>
